package no.ntnu.item.ttm4115.termproject.playeragent.gui;

import java.util.HashMap;
import java.util.Vector;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;

import com.thoughtworks.xstream.XStream;

import no.ntnu.item.ttm4115.termproject.Alternative;
import no.ntnu.item.ttm4115.termproject.InvitePlayer;
import no.ntnu.item.ttm4115.termproject.Invitees;
import no.ntnu.item.ttm4115.termproject.PlayerAddedGroup;
import no.ntnu.item.ttm4115.termproject.SendRoleRequestToNewGroup;
import no.ntnu.item.ttm4115.termproject.extrasagent.Group;
import no.ntnu.item.ttm4115.termproject.extrasagent.Player;
import no.tellu.common.actorframe.ActorSM;
import no.tellu.common.javaframe.ActorAddress;

/*
 * NewGroupDialog.java
 *
 * Created on 16. juli 2008, 10:20
 */

/**
 *
 * @author  Kim A Martinsen
 */

public class NewGroupDialog extends javax.swing.JFrame {

    // Variables declaration - do not modify
    private javax.swing.JButton jButtonApply;
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JButton jButtonInvite;
    private javax.swing.JButton jButtonRemove;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JCheckBox jCheckBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabelInfo1;
    private javax.swing.JLabel jLabelInfo2;
    private javax.swing.JLabel jLabelName;
    private javax.swing.JList jListInvited;
    private javax.swing.JList jListPlayer;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanelBackGround;
    private javax.swing.JPanel jPanelInvite;
    private javax.swing.JScrollPane jScrollPaneInvited;
    private javax.swing.JScrollPane jScrollPanePlayers;
    private javax.swing.JTextField jTextFieldNameInput;
    private DefaultListModel jListOnlinePlayersModel;
    private DefaultListModel jListInvitedPlayersModel;
	private ActorSM asm;
	private Vector<Player> playerConfig;
	private Player me;
	private ActorAddress classManager;
    // End of variables declaration
	
	

    public NewGroupDialog(ActorSM asm, Vector playerConfig, Player player, ActorAddress classManager) {
    	this.playerConfig = playerConfig;
    	this.asm = asm;
    	me = player;
    	this.classManager = classManager;
    	
    	
        initComponents();
    }
    
    @SuppressWarnings("unchecked")
    private void initComponents() {

        jPanelBackGround = new javax.swing.JPanel();
        jPanelInvite = new javax.swing.JPanel();
        jScrollPanePlayers = new javax.swing.JScrollPane();
        jListPlayer = new javax.swing.JList();
        jScrollPaneInvited = new javax.swing.JScrollPane();
        jListInvited = new javax.swing.JList();
        jLabelInfo1 = new javax.swing.JLabel();
        jLabelInfo2 = new javax.swing.JLabel();
        jButtonInvite = new javax.swing.JButton();
        jButtonRemove = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabelName = new javax.swing.JLabel();
        jTextFieldNameInput = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jCheckBox1 = new javax.swing.JCheckBox();
        jCheckBox2 = new javax.swing.JCheckBox();
        jButtonApply = new javax.swing.JButton();
        jButtonCancel = new javax.swing.JButton();
        jListInvitedPlayersModel = new DefaultListModel();
        jListOnlinePlayersModel = new DefaultListModel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Add New Group");

        jPanelInvite.setBorder(javax.swing.BorderFactory.createTitledBorder("Invite Players"));

        fillOnlinePlayersList(getJListOnlinePlayersModel());
        jListPlayer.setModel(getJListOnlinePlayersModel());
        jScrollPanePlayers.setViewportView(jListPlayer);

        fillInvitedPlayersList(getJListInvitedPlayersModel());
        jListInvited.setModel(getJListInvitedPlayersModel());
        jScrollPaneInvited.setViewportView(jListInvited);

        jLabelInfo1.setText("Select all the players to the right that you wish to invite");

        jLabelInfo2.setText("to your group ");

        jButtonInvite.setIcon(new javax.swing.ImageIcon(getClass().getResource("001_27.png"))); // NOI18N
        jButtonInvite.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonInviteActionPerformed(evt);
            }
        });
        jButtonRemove.setIcon(new javax.swing.ImageIcon(getClass().getResource("001_25.png"))); // NOI18N
        jButtonRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRemoveActionPerformed(evt);
            }
        });
        
        javax.swing.GroupLayout jPanelInviteLayout = new javax.swing.GroupLayout(jPanelInvite);
        jPanelInvite.setLayout(jPanelInviteLayout);
        jPanelInviteLayout.setHorizontalGroup(
            jPanelInviteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelInviteLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelInviteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelInviteLayout.createSequentialGroup()
                        .addComponent(jScrollPaneInvited, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanelInviteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jButtonInvite, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButtonRemove, 0, 0, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPanePlayers, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(8, 8, 8))
                    .addComponent(jLabelInfo1)
                    .addComponent(jLabelInfo2))
                .addContainerGap())
        );
        jPanelInviteLayout.setVerticalGroup(
            jPanelInviteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelInviteLayout.createSequentialGroup()
                .addComponent(jLabelInfo1)
                .addGroup(jPanelInviteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelInviteLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPanePlayers, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelInviteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanelInviteLayout.createSequentialGroup()
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jLabelInfo2)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE)
                            .addComponent(jScrollPaneInvited, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanelInviteLayout.createSequentialGroup()
                            .addGap(96, 96, 96)
                            .addComponent(jButtonInvite)
                            .addGap(18, 18, 18)
                            .addComponent(jButtonRemove))))
                .addContainerGap())
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("New Group"));

        jLabelName.setText("Name:");

        jLabel1.setText("Set Group Rights:");

        jCheckBox1.setText("Group Chat");

        jCheckBox2.setText("Group Discussion");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabelName)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTextFieldNameInput, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE))
                    .addComponent(jLabel1)
                    .addComponent(jCheckBox1)
                    .addComponent(jCheckBox2))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelName)
                    .addComponent(jTextFieldNameInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(36, 36, 36)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jCheckBox1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jCheckBox2)
                .addContainerGap(133, Short.MAX_VALUE))
        );

        jButtonApply.setIcon(new javax.swing.ImageIcon(getClass().getResource("001_06.png"))); // NOI18N
        jButtonApply.setText("Apply");
        jButtonApply.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonApplyActionPerformed(evt);
            }
        });

        jButtonCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("001_05.png"))); // NOI18N
        jButtonCancel.setText("Cancel");
        jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanelBackGroundLayout = new javax.swing.GroupLayout(jPanelBackGround);
        jPanelBackGround.setLayout(jPanelBackGroundLayout);
        jPanelBackGroundLayout.setHorizontalGroup(
            jPanelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelBackGroundLayout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanelInvite, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelBackGroundLayout.createSequentialGroup()
                .addContainerGap(402, Short.MAX_VALUE)
                .addComponent(jButtonCancel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonApply, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanelBackGroundLayout.setVerticalGroup(
            jPanelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelBackGroundLayout.createSequentialGroup()
                .addGroup(jPanelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanelInvite, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonCancel)
                    .addComponent(jButtonApply))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelBackGround, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanelBackGround, javax.swing.GroupLayout.DEFAULT_SIZE, 363, Short.MAX_VALUE)
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-610)/2, (screenSize.height-408)/2, 610, 408);
    }// </editor-fold>

private void jButtonApplyActionPerformed(java.awt.event.ActionEvent evt) {

	Vector<Player> addMe = new Vector<Player>();
	addMe.add(me);
	Group newGroup = new Group();
	newGroup.setChat(true);
	newGroup.setDiscussion(true);
	newGroup.setIm(true);
	newGroup.setGroupName(jTextFieldNameInput.getText());
	newGroup.setPlayers(addMe);
	XStream xstream = new XStream();
	xstream.setClassLoader(new Player().getClass().getClassLoader());
	xstream.alias("player", Player.class);
	xstream.alias("group", Group.class);
	xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);
	
	me.addGroup(newGroup);
	
	String group = xstream.toXML(newGroup);
	String player = xstream.toXML(me);
	
	
	
	Vector<String> groupPlayersVector = new Vector<String>();
	for(int i=0; i<getJListInvitedPlayersModel().getSize();i++){
		groupPlayersVector.add((String) getJListInvitedPlayersModel().getElementAt(i));
	}
	
	asm.sendMessage(new Invitees(groupPlayersVector), asm.getMyActorAddress());
	//asm.sendMessage(PlayerAddedGroup(group,signal)
	asm.sendMessage(new SendRoleRequestToNewGroup(player, newGroup.getGroupName()),asm.getMyActorAddress());
	
	this.dispose();
}

private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {
	this.dispose();
}

private void jButtonInviteActionPerformed(java.awt.event.ActionEvent evt) {
	Object[] playersToBeAdded =  jListPlayer.getSelectedValues();
	System.out.println(playersToBeAdded[0]);
	fillAddedPlayersList(playersToBeAdded);
}

private void jButtonRemoveActionPerformed(java.awt.event.ActionEvent evt) {
	Object[] playersToBeRemoved =  jListInvited.getSelectedValues();
	removePlayersFromAddedList(playersToBeRemoved);
}

private DefaultListModel getJListOnlinePlayersModel(){
	return jListOnlinePlayersModel;
}

private DefaultListModel getJListInvitedPlayersModel(){
	return jListInvitedPlayersModel;
}

private void fillOnlinePlayersList(DefaultListModel model){
	model.removeAllElements();
	for (int i = 0; i < playerConfig.size(); i++) {
		if(!me.getUserName().equals(playerConfig.elementAt(i).getUserName())){
			String player = (String)playerConfig.elementAt(i).getUserName();
			model.addElement(player);
		}

	}
}

private void fillInvitedPlayersList(DefaultListModel model){
	model.removeAllElements();
}


private void fillAddedPlayersList(Object[] players){
	if(players != null){
		for(int i=0; i<players.length;i++){
			if(checkAddedPlayersList((String) players[i])){
				jListInvitedPlayersModel.addElement((players[i]));
			}
		}
	}
	jListInvited.repaint();
}



private boolean checkAddedPlayersList(String player){
	boolean booleanValue = true;
	for(int i=0; i<getJListInvitedPlayersModel().getSize();i++){
		if(getJListInvitedPlayersModel().getElementAt(i)==player){
			booleanValue = false;
			break;
		}
	}
	return booleanValue;
}


private void removePlayersFromAddedList(Object[] players){
	if(players != null){
		for (int i = 0; i < players.length; i++) {
			for (int j = 0; j < getJListInvitedPlayersModel().size(); j++) {
				if(players[i].equals(getJListInvitedPlayersModel().elementAt(j))){
					getJListInvitedPlayersModel().remove(j);
				}
			}
		}
	}
}

private HashMap<String, ActorAddress> sendInvitesToAll(Vector<String> stringVector){
	HashMap<String, ActorAddress> tempMap = new HashMap<String, ActorAddress>();
	
	for (int i = 0; i < stringVector.size(); i++) {
		for (int j = 0; j < playerConfig.size(); j++) {
			if(stringVector.elementAt(i).toString().equals(playerConfig.elementAt(j).getUserName().toString())){
				tempMap.put(playerConfig.elementAt(i).getUserName(), playerConfig.elementAt(j).getActorAddress());
			}
		}
	}
	return tempMap;
} 

}

